package com.wyd.flowable.listener;

import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.AbstractFlowableEventListener;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.springframework.stereotype.Service;

/**
 * @author 王叶东
 * @since 2023/12/20 14:22
 */
@Slf4j
@Service
public class TestListener extends AbstractFlowableEventListener {
    @Override
    public void onEvent(FlowableEvent event) {
//        log.info("type={} class={} event={} ", event.getType(), event.getClass().getName(), event);

        if (FlowableEngineEventType.PROCESS_CREATED.equals(event.getType())) {
            final Object entity = ((FlowableEntityEvent) event).getEntity();
            log.info("流程已创建事件 entityClass={} entity={} ", entity.getClass().getName(), entity);

            final ExecutionEntityImpl executionEntity = (ExecutionEntityImpl) ((FlowableEntityEvent) event).getEntity();

//            executionEntity.setBusinessStatus("test");
//            executionEntity.forceUpdate();
        } else if (FlowableEngineEventType.ENTITY_CREATED.equals(event.getType())) {
            final Object entity = ((FlowableEntityEvent) event).getEntity();
            log.info("实体已创建事件 entityClass={} entity={} ", entity.getClass().getName(), entity);

            if (entity instanceof ExecutionEntityImpl) {
                final ExecutionEntityImpl executionEntity = (ExecutionEntityImpl) entity;
                final String parentId = executionEntity.getParentId();

                if (parentId == null) {
                    executionEntity.setBusinessStatus("test1");
                }
            }
        }
    }

    @Override
    public boolean isFailOnException() {
        return true;
    }
}
